package light.head.controller.site;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.config.ConfigParm;
import light.head.config.RunStatus;
import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.site.CertificatesAnnexDAO;
import light.head.dao.site.CertificatesDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.Certificates;
import light.head.model.CertificatesAnnex;
import light.head.model.FileInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(Url.CERTIFICATES)
public class CertificatesController extends SupporterController{
	private CertificatesDAO cDAO;
	private CertificatesAnnexDAO caDAO;
	
	private	final static String upload_path = "upload/certificatesAnnex/";
	
	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.CERTIFICATES_INIT);
	}

	@RequestMapping(Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.NAME, Parm.DELETED, Parm.OC);
		if (cDAO.findByMap(map, pb) == RESULT.SUCCESS){
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}		
		return new ModelAndView(Url.CERTIFICATES_LIST);
	}
	
	@RequestMapping(Url.EDIT)
	public ModelAndView edit(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null != code) {
			Certificates c = cDAO.get(code);
			List<CertificatesAnnex> list = cDAO.findAnnexByCode(code);
			request.setAttribute(Parm.LIST, list);
			request.setAttribute(Parm.CERTIFICATES, c);
		}
		return new ModelAndView(Url.CERTIFICATES_DEIT);
	}
	
	@RequestMapping(value = Url.SAVE)
	public void save(Certificates c,HttpServletRequest request, HttpServletResponse response) throws Exception {
		String fileCode=request.getParameter("fileCode");
		String choose =request.getParameter("choose");
		RESULT result = RESULT.ERROR;
		if (c.getCode() != null) {
			List<CertificatesAnnex> list=caDAO.getByCc(c.getCode());
			if(list != null){
				for(int i=0;i<list.size();i++){
					list.get(i).setCover(false);
					caDAO.upd(list.get(i));
				}
				if(choose != null){
					CertificatesAnnex ca = caDAO.get(Integer.parseInt(choose));
					ca.setCover(true);
					caDAO.upd(ca);
				}
			}
			result = cDAO.upd(c);
		} else {
			c.setCt(new Date());
			c.setCu(cu_code(request));
			c.setOc(cu_organCode(request));
			c.setDeleted(false);
			result = cDAO.add(c);
		}
		if (result == RESULT.SUCCESS) {
			List<Object> noDelCodes = new ArrayList<Object>();
			if (null != c.getList() && c.getList().size() > 0) {
				for (CertificatesAnnex ca : c.getList()) {
					noDelCodes.add(ca.getCode());
				}
			}
			String[] afcs = request.getParameterValues(Parm.AFCS);
			if (null != afcs && afcs.length > 0) {
				StringBuffer codes = new StringBuffer();
				for (String code : afcs) {
					codes.append(code + Sys.COMMA);
				}
				codes.deleteCharAt(codes.length() - 1);
				List<FileInfo> list = cDAO.findFileByCodes(codes.toString());
				if (null != list && list.size() > 0) {
					CertificatesAnnex temp = null;
					for (FileInfo fi : list) {
						temp = new CertificatesAnnex();
						temp.setExt(fi.getExt());
						temp.setCc(c.getCode());
						temp.setName(fi.getName());
						temp.setSize(fi.getSize());
						temp.setSn(fi.getUuid());
						if(fileCode != null && Integer.parseInt(fileCode) == fi.getCode()){
							temp.setCover(true);
						}else{
							temp.setCover(false);
						}
						cDAO.add(temp);
						noDelCodes.add(temp.getCode());
					}
				}
			}
			cDAO.deleteAnnexNotInCodes(c.getCode(), noDelCodes);
			RunStatus.pcIndexCreateState = Sys.B_ZERO;
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
	}
	
	@RequestMapping(value = Url.DELETE)
	public void delete(Integer code,Byte type,HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		if(code!=null){
			Certificates c = cDAO.get(code);
			c.setDeleted(true);
			result=cDAO.upd(c);
		}
		if(result==RESULT.SUCCESS){
			print(response, Msg.SUCCESS);
		}else{
			print(response, Msg.ERROR);
		}
	}
	
	@Transactional
	@RequestMapping(Url.UPLOADS)
	public void uploads(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		List<MultipartFile> files = multipartRequest.getFiles("files");
		StringBuffer result = new StringBuffer("");
		if (null != files && files.size() > 0) {
			String name = null;
			String ext = null;
			String uuid = null;
			String path = null;
			String savePath = null;
			UUID u = null;
			for (MultipartFile mf : files) {
				name = mf.getOriginalFilename();
				if (isNotNull(name)) {
					ext = name.substring(name.lastIndexOf('.') + 1);
					if (!ext.toUpperCase().equals(Sys.JPG) && !ext.toUpperCase().equals(Sys.GIF)
							&& !ext.toUpperCase().equals(Sys.JPEG) && !ext.toUpperCase().equals(Sys.BMP)
							&& !ext.toUpperCase().equals(Sys.PNG)  && !ext.toUpperCase().equals(Sys.XLSX)
							&& !ext.toUpperCase().equals(Sys.XLS)  && !ext.toUpperCase().equals(Sys.DOCX)
							&& !ext.toUpperCase().equals(Sys.DOC)  && !ext.toUpperCase().equals(Sys.PDF)
							&& !ext.toUpperCase().equals(Sys.PPT)  && !ext.toUpperCase().equals(Sys.RAR)
							&& !ext.toUpperCase().equals(Sys.ZIP)) {
						print(response, Msg.J_FILE_TYPE_ERROR);
						return;
					}
					name = name.substring(0, name.lastIndexOf('.'));
					u = UUID.randomUUID();
					uuid = u.toString().replace("-", "");
					path = upload_path + uuid + Sys.DOT + ext;
					savePath = ConfigParm.getProjectPath() + path;
					FileOutputStream fo;
					int size = 0;
					try {
						fo = new FileOutputStream(savePath);
						size = mf.getBytes().length;
						fo.write(mf.getBytes());
						fo.close();
					} catch (Exception e) {
						print(response, Msg.ERROR);
						e.printStackTrace();
					}

					FileInfo f = new FileInfo();
					f.setDeleted(false);
					f.setExt(ext);
					f.setName(name);
					f.setUuid(uuid);
					f.setCt(new Date());
					f.setType(isImg(ext) ? Sys.B_TWO : Sys.ONE);
					f.setModule(Parm.CERTIFICATESANNEX);
					f.setCu(cu_code(request));
					f.setOc(cu_organCode(request));
					f.setSize(size);
					cDAO.add(f);
					result.append("{\"name\":\"" + name + "\",\"code\":\""+ f.getCode() + "\",\"ext\":\"" + ext+ "\",\"size\":\"" + size + "\",\"path\":\"" + uuid+ Sys.DOT + ext + "\"},");
				}
			}
			result.insert(0, "{\"result\":\"success\",\"list\":[").deleteCharAt(result.length() - 1).append("]}");
			print(response, result.toString());
		} else {
			result.append("{\"result\":\"not_find_file\"}");
		}
	}

	private boolean isImg(String ext) {
		if (!isNotNull(ext))
			return false;
		if (ext.toUpperCase().equals(Sys.JPG)
				|| ext.toUpperCase().equals(Sys.GIF)
				|| ext.toUpperCase().equals(Sys.JPEG)
				|| ext.toUpperCase().equals(Sys.BMP)
				|| ext.toUpperCase().equals(Sys.PNG)) {
			return true;
		}
		return false;
	}
	
	@Autowired
	public void setcDAO(CertificatesDAO cDAO) {
		this.cDAO = cDAO;
	}
	@Autowired
	public void setCaDAO(CertificatesAnnexDAO caDAO) {
		this.caDAO = caDAO;
	}
}
